<template>
  <div>
    <a-input-search
      placeholder="input search text"
      style="width: 300px"
      @search="onSearch"
    />
    <a-button type="primary" @click="showDrawer(false)">添加用户</a-button>
    <!-- columns列，data-source数据源 -->
    <a-table
      :columns="columns"
      :data-source="userData"
      bordered
      :pagination="false"
      rowKey="id"
    >
      <!-- 作用域插槽，父组件使用子组件的内容 -->
      <template #state="{ text, record }">
        <a-switch :checked="text" @click="changeState(record.id, !text)" />
      </template>
      <template #btn="{ record }">
        <a-tooltip placement="top">
          <template #title>
            <span>编辑</span>
          </template>
          <a-button type="primary" shape="circle" @click="showDrawer(record)">
            <template #icon><EditOutlined /></template>
          </a-button>
        </a-tooltip>
        <a-tooltip placement="top">
          <template #title>
            <span>删除</span>
          </template>
          <a-button type="danger" shape="circle" @click="removeUser(record.id)">
            <template #icon><CloseOutlined /></template>
          </a-button>
        </a-tooltip>
        <a-tooltip placement="top">
          <template #title>
            <span>分配角色</span>
          </template>
          <a-button
            type="primary"
            shape="circle"
            @click="roleVisibleBox(record)"
          >
            <template #icon><ToolOutlined /></template>
          </a-button>
        </a-tooltip>
      </template>
    </a-table>
    <!-- 对话框 -->
    <a-modal v-model:visible="roleVisible" title="分配角色" @ok="handleOk">
      <p>当前用户：{{ currentRole.username }}</p>
      <p>当前角色：{{ currentRole.rolename }}</p>
      <p>
        选中角色：
        <a-select v-model:value="selectValue" style="width: 120px">
          <a-select-option
            :value="item.id"
            v-for="item in roleList"
            :key="item.id"
            >{{ item.roleName }}</a-select-option
          >
        </a-select>
      </p>
    </a-modal>
    <a-config-provider :locale="locale">
      <a-pagination
        :total="total"
        :pageSizeOptions="['1', '2', '5', '10']"
        :defaultPageSize="2"
        @change="pageChange"
        @showSizeChange="pageSizeChange"
        show-size-changer
        show-quick-jumper
      />
    </a-config-provider>
    <a-config-provider :locale="locale">
      <a-drawer
        title="Create a new account"
        :width="720"
        :visible="visible"
        :body-style="{ paddingBottom: '80px' }"
        @close="onClose"
      >
        <a-form :model="form" :rules="rules" layout="vertical" ref="formRef">
          <a-row :gutter="16">
            <a-col :span="16">
              <a-form-item label="Username" name="username">
                <a-input
                  :disabled="operationFlag"
                  v-model:value="form.username"
                  placeholder="Please enter user name"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16" v-if="!operationFlag">
            <a-col :span="16">
              <a-form-item label="Password" name="password">
                <a-input
                  v-model:value="form.password"
                  placeholder="Please enter user password"
                />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="16">
              <a-form-item label="Email" name="email">
                <a-input v-model:value="form.email" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :gutter="16">
            <a-col :span="16">
              <a-form-item label="Mobile" name="mobile">
                <a-input v-model:value="form.mobile" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
        <div
          :style="{
            position: 'absolute',
            right: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
            zIndex: 1,
          }"
        >
          <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
          <a-button type="primary" @click="onSubmit">提交</a-button>
        </div>
      </a-drawer>
    </a-config-provider>
  </div>
</template>

<script>
import { CloseOutlined, EditOutlined, ToolOutlined } from '@ant-design/icons-vue';
import { getCurrentInstance, onMounted, ref, reactive, toRaw } from 'vue';
import zhCN from 'ant-design-vue/es/locale/zh_CN';
import { message } from 'ant-design-vue';
export default {
  components: {
    CloseOutlined,
    EditOutlined,
    ToolOutlined
  },
  setup () {
    const { proxy } = getCurrentInstance()
    // 表头（表格依赖）
    const columns = [
      {
        title: 'Id',
        dataIndex: 'id',

      },
      {
        title: '用户名',
        // 添加类名
        className: 'column-money',
        // 数据
        dataIndex: 'username',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
      },
      {
        title: '电话',
        dataIndex: 'mobile',
      },
      {
        title: '角色',
        dataIndex: 'role_name',
      },
      {
        title: '状态',
        dataIndex: 'mg_state',
        slots: { customRender: 'state' }
      },
      {
        title: '操作',
        slots: { customRender: 'btn' }

      }
    ];
    // 这一页的用户数据（表格依赖）
    let userData = ref();
    // 请求参数：第几页与几条
    const queryParams = {
      query: '',
      pagenum: 1,
      pagesize: 2
    }
    // 共几条用户数据
    const total = ref()
    // 请求数据
    const quertyData = async () => {
      const { data } = await proxy.$http.get('users', {
        params: queryParams
      })
      total.value = data.total
      console.log(total.value);
      userData.value = data.users
      console.log(data);
    }
    const onSearch = (val) => {
      console.log(val);
    }
    // 点击换页
    const pageChange = (page, pageSize) => {
      queryParams.pagenum = page
      queryParams.pagesize = pageSize
      quertyData()
    }
    // 点击每页几条
    const pageSizeChange = (urrent, size) => {
      queryParams.pagenum = urrent
      queryParams.pagesize = size
      quertyData()
    }
    const formRef = ref()
    // 控制抽屉
    const visible = ref(false)
    // 点击弹出添加用户抽屉
    const operationFlag = ref(false)
    const showDrawer = (data) => {
      const res = toRaw(data)
      if (data) {
        form.username = res.username
        form.email = res.email
        form.mobile = res.mobile
        operationFlag.value = res
      } else {
        operationFlag.value = false
        form.username = ''
        form.email = ''
        form.mobile = ''
      }
      visible.value = true;
    };
    // 关闭添加用户抽屉
    const onClose = () => {
      visible.value = false;
      message.info('已取消')
    };

    // 添加用户或修改用户
    const onSubmit = async () => {
      if (operationFlag.value) {
        const params = {
          email: form.email,
          mobile: form.mobile
        }
        var { meta } = await proxy.$http.put(`users/${operationFlag.value.id}`, params)
        if (meta.status !== 200) return message.error(meta.msg)
      } else {
        var { meta } = await proxy.$http.post('users', form)
        if (meta.status !== 201) return message.error(meta.msg)
      }
      message.success(meta.msg)
      quertyData()
      formRef.value.resetFields()
      visible.value = false;
    }
    const form = reactive({
      username: '',
      password: '',
      email: '',
      mobile: ''
    });
    const rules = {
      username: [
        {
          required: true,
          message: '请输入用户名',
          trigger: 'blur'
        }
      ],
      password: [
        {
          required: true,
          message: '请输入密码',
          trigger: 'blur'
        }
      ],
      email: [
        {
          required: false
        }
      ],
      mobile: [
        {
          required: false
        }
      ],
    };
    // 更改状态
    const changeState = async (id, state) => {
      const { meta } = await proxy.$http.put(`users/${id}/state/${state}`)
      if (meta.status !== 200) return message.error(meta.msg)
      message.success(meta.msg)
      quertyData()
    }
    // 删除用户
    const removeUser = async (id) => {
      const { meta } = await proxy.$http.delete(`users/${id}`)
      console.log(meta);
      if (meta.status !== 200) return message.error(meta.msg)
      message.success(meta.msg)
      quertyData()
    }
    // 分配角色盒子显示隐藏
    const roleVisible = ref(false)
    // 分配角色盒子点击确定
    const handleOk = async () => {
      if (selectValue.value == '请选择') return message.error('请选择一项')
      const { meta } = await proxy.$http.put(`users/${currentRole.id}/role`, {
        rid: selectValue.value
      })
      if (meta.status !== 200) return message.error(meta.msg)
      selectValue.value = '请选择'
      message.success(meta.msg)
      roleVisible.value = false
      quertyData()
    }
    // 当前选中的角色
    const selectValue = ref('请选择')
    // 当前用户当前角色当前id
    const currentRole = reactive({})
    // 所有可选角色
    const roleList = ref([])
    // 点击弹出分配角色对话框，并在插槽中拿到数据
    const roleVisibleBox = async ({ id, username, role_name }) => {
      currentRole.id = id
      currentRole.username = username
      currentRole.rolename = role_name
      const { meta, data } = await proxy.$http.get('roles')
      if (meta.status !== 200) return message.error(meta.msg)
      roleList.value = data
      console.log(roleList.value);
      roleVisible.value = true
    }
    onMounted(() => {
      quertyData()
    })
    return {
      onSearch,
      userData,
      columns,
      locale: zhCN,
      pageChange,
      pageSizeChange,
      total,
      showDrawer,
      onClose,
      visible,
      rules,
      form,
      onSubmit,
      changeState,
      removeUser,
      operationFlag,
      formRef,
      roleVisible,
      handleOk,
      roleVisibleBox,
      currentRole,
      selectValue,
      roleList
    }
  }
}
</script>
<style lang="less" scoped>
.ant-input-search {
  margin-right: 10px;
  margin-bottom: 20px;
}
</style>
<style lang="less">
.column-money {
  color: #f00;
}
.ant-btn-icon-only {
  margin: 0 2px;
}
.ant-pagination {
  margin-top: 30px;
}
</style>